package top.lileix.mybatis.generator.x.kit;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import top.lileix.mybatis.generator.x.domain.Table;
import top.lileix.mybatis.generator.x.domain.mapper.Result;
import top.lileix.mybatis.generator.x.domain.mapper.ResultMap;

public class MybatisXMLTool {

    public static String insert(Table t, ResultMap resultMap) {
	StringBuilder sb = new StringBuilder("insert into ").append(t.getTableName()).append("");
	sb.append("<trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\">");
	List<Result> rs = new ArrayList<>(resultMap.results);
	rs.add(resultMap.id);
	for (Result e : rs) {
	    sb.append("<if test=\"");
	    sb.append(e.property);
	    sb.append("!=null\">");
	    sb.append(e.column);
	    sb.append(",</if>");
	}
	sb.append("</trim>" + "<trim prefix=\"values (\" suffix=\")\" suffixOverrides=\",\">");
	for (Result e : rs) {
	    sb.append("<if test=\"");
	    sb.append(e.property);
	    sb.append("!=null\">");
	    sb.append("#{");
	    sb.append(e.property);
	    sb.append("}");
	    sb.append(",</if>");

	}
	sb.append("</trim>");
	return sb.toString();
    }

    @SuppressWarnings("unchecked")
    public static void update(String pathname) throws DocumentException {

	// 创建SAXReader对象
	SAXReader reader = new SAXReader();
	// 读取文件 转换成Document
	Document document = reader.read(new File(pathname));
	Element resultMap = document.getRootElement().element("resultMap");
	List<Element> iterator = resultMap.elements("result");
	System.out.println("<set>");
	for (Element element : iterator) {
	    String s = "<if test=\"";
	    s += element.attributeValue("property");
	    s += "!=null\">";
	    s += element.attributeValue("column");
	    s += "=#{" + element.attributeValue("property") + "}";
	    s += ",</if>";
	    System.out.println(s);
	}

	System.out.println("</set>");

    }

    public static void all(String pathname) throws DocumentException {

	// 创建SAXReader对象
	SAXReader reader = new SAXReader();
	// 读取文件 转换成Document
	Document document = reader.read(new File(pathname));
	Element resultMap = document.getRootElement().element("resultMap");
	@SuppressWarnings("unchecked")
	List<Element> iterator = resultMap.elements();
	String s = "";
	for (Element element : iterator) {
	    s += element.attributeValue("column") + ",";
	}
	System.out.println(s);

    }
}
